require 'faye/websocket'
require 'eventmachine'
require 'zlib'
require 'json'
require 'redis'

Redis.current = Redis.new(host: 'alihk', port: 6379)

def redis
  Redis.current
end

def subscribe(socket)
  pairs = %w[btcusdt xrpusdt]
  operations = %w[market.#.depth.step0 market.#.bbo]
  operations.each do |operation|
    pairs.each do |pair|
      sub_command = { sub: operation.gsub(/#/, pair),
                      id: operation.gsub(/#/, pair) + 'wx' }.to_json
      socket.send(sub_command)
    end
  end
end

EM.run do
  ws = Faye::WebSocket::Client.new('wss://api.huobi.pro/ws')

  ws.on :open do |_event|
    p [:open]
    subscribe(ws)
    # ws.send('Hello, world!')
  end

  ws.on :message do |event|
    u = event.data.pack('c*')
    zstream = Zlib::Inflate.new(16 + Zlib::MAX_WBITS)
    buf = zstream.inflate(u)
    msg = JSON.parse(buf)
    # p msg
    if msg['ping']
      p msg['ping']
      ws.send({ pong: msg['ping'] }.to_json)
      redis.publish('blockchain', msg['ping'])
    end
    # p msg
  end

  ws.on :close do |event|
    p [:close, event.code, event.reason]
    ws = nil
    exit 1
  end
end
